﻿using System.Text;
using System.Threading;
using Lidgren.Network;
using NetBrick.Common.Packets;
using UniBrickCommon;
using UniBrickCommon.Packets;
using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class Connection : MonoBehaviour
{
    public static Connection Instance { get; private set; }
    public static GameClient GameClient { get; private set; }

    public Transform MinifigModel;
    public InputField UsernameText;
    public InputField PasswordText;
    public bool GameStarted { get; set; }

    void OnApplicationQuit()
    {
        GameClient.Disconnect("User quit.");
        GameClient.Shutdown();
    }

    void Start()
    {
        if (Instance != null)
        {
            Destroy(this);
        }
        else
        {
            Instance = this;
            DontDestroyOnLoad(this);
        }
        GameClient = new GameClient(MinifigModel);
        StartCoroutine(Listen());
        GameClient.Connect(CommonConstants.IpAddress, CommonConstants.Port);
    }

    public IEnumerator Listen()
    {
        Debug.Log("t");
        while (!GameClient.ShuttingDown)
        {
            Debug.Log("t");
            GameClient.Update();
            yield return null;
        }
    }

    public void Login()
    {
        Debug.Log("Logging in.");
        if (!GameClient.EncryptionAvailable)
            return;
        Debug.Log("Sending packet.");
        var authPacket = new AuthenticatePacket.Request(UsernameText.text, GameClient.Encrypt(Encoding.UTF8.GetBytes(PasswordText.text)));
        GameClient.SendPacket(UniBrickPacketCode.AuthenticateRequest, authPacket, NetDeliveryMethod.ReliableOrdered);
    }
}